<?php
namespace app\index;

use think\Cookie;
use think\Cache;
use think\View;
use think\Request;
use think\Config;
use think\exception\HttpException;
use think\Db;
use think\Session;

class Controller
{
    /**
     * @var View 视图类实例
     */
    protected $view;
    /**
     * @var Request Request实例
     */
    protected $request;

    /**
     * 京东appKey,appSecret,serverUrl
     * @var Jd JdSdk实例
     */
    protected $appKey = '1E52570E2F6D56F13344E2AF7C2789D1';
    protected $appSecret = '99e9df0a13d3441885e3f915cd73d259';
    protected $serverUrl = 'https://api.jd.com/routerjson';
    protected $jd;

    public function __construct()
    {
        if (null === $this->view) {
            $this->view = View::instance(Config::get('template'), Config::get('view_replace_str'));
        }
        if (null === $this->request) {
            $this->request = Request::instance();
        }
        require_once(ROOT_PATH . 'sdks' . DS . 'jd_jos' . DS . 'JdSdk.php');
        $this->jd = new \JdClient();
        $this->jd->appKey = $this->appKey;
        $this->jd->appSecret = $this->appSecret;
        $this->jd->serverUrl = $this->serverUrl;
    }

    /**
     * 根据分类product_sort_ids ,获取商品分类信息
     * @param string $ids ,可批量查询分类ID,中间用逗号分隔
     * @return array
     */
    public function classInfoByclassId($ids)
    {
        $req = new \WareProductsortGetRequest();
        $req->setProductSortIds($ids);
        $resp = $this->jd->execute($req);
        return json_decode(json_encode($resp),true);
    }

    /**
     * 根据商品skuId ,获取商品基本信息
     * @param string $ids ,可批量查询商品ID,中间用逗号分隔,最大不超过10
     * @param string $basefields ,需要查询的字段,与返回值ProductBase中的字段对应
     * @return array
     */
    public function goodsInfoBygoodsId($ids, $basefields = 'skuId,name,isDelete,state,barCode,erpPid,color,colorSequence,size,sizeSequence,upc,skuMark,saleDate,cid2,valueWeight,weight,productArea,wserve,allnum,maxPurchQty,brandId,valuePayFirst,length,width,height,venderType,pname,issn,safeDays,saleUnit,packSpecification,category,shopCategorys,phone,site,ebrand,cbrand,model,imagePath,shopName,url')
    {
        $req = new \NewWareBaseproductGetRequest();
        $req->setIds($ids);
        $req->setBasefields($basefields);
        $resp = $this->jd->execute($req);
        return json_decode(json_encode($resp),true)['listproductbase_result'];
    }

    /**
     * 根据SKU ID ,获取商品价格信息
     * @param string $sku_ids ,特别注意,请以大写J_作为开头skuid,否则无法正确返回,每次只能查询一个
     * @return array
     */
    public function goodsPriceBySkuId($sku_ids)
    {
        $req = new \WarePriceGetRequest();
        $req->setSkuId($sku_ids);
        $resp = $this->jd->execute($req);
        return json_decode(json_encode($resp),true)['price_changes'][0];
    }

    /**
     * 根据ID ,查询同类产品ids
     * @param string $id ,可批量查询,中间用逗号分隔
     * @return array
     */
    public function idsPriceById($id)
    {
        $req = new \NewWareSameproductskuidsQueryRequest();
        $req->setId($id);
        $resp = $this->jd->execute($req);
        return json_decode(json_encode($resp),true)['result'];
    }

    /**
     * 根据key ,商品搜索（平搜）
     * @param string $key ,关键字(文本需要gbk编码)
     * @param int $goodsPage ,第几页(默认1)
     * @param string $typeId ,过滤参数
     * @return array
     */
    public function goodsSearchByKey($key,$goodsPage = 1,$typeId = null)
    {
        $req = new \SearchWareRequest();
        $key = urlencode(iconv('UTF-8', 'GBK', $key));
        $req->setKey($key);
        $req->setFiltType($typeId);
        $req->setPage($goodsPage);
        /*$req->setAreaIds("jingdong");
        $req->setSortType("jingdong");*/

        $resp = $this->jd->execute($req);
        return json_decode(json_encode($resp),true);
    }

    /**
     * 根据key ,店铺搜索
     * @param string $key ,关键字(文本需要gbk编码)
     * @param string $typeId ,过滤参数
     * @param int $pagesize ,页大小
     * @param int $shopsPage ,第几页(默认1)
     * @return array
     */
    public function shopsSearchByKey($key,$typeId = null,$pagesize = 10,$shopsPage = 1)
    {
        $req = new \ShopSearchRequest();    //该接口SDK里找不着
        $key = urlencode(iconv('UTF-8', 'GBK', $key));
        $req->setKey($key);
        $req->setFiltType($typeId);
        $req->setPagesize($pagesize);
        $req->setPage($shopsPage);

        $resp = $this->jd->execute($req);
        return json_decode(json_encode($resp),true);
    }

    /**
     * 移动商品介绍 ,根据SKU ID 查询
     * @param string $id ,可批量查询,中间用逗号分隔
     * @return array
     */
    public function mobileGoodsInfoBySkuId($id)
    {
        $req = new \NewWareMobilebigfieldGetRequest();
        $req->setSkuid($id);
        $resp = $this->jd->execute($req);
        return json_decode(json_encode($resp),true)['result'];
    }


    /**
     * 格式化商品分类id，将 ; : 转为 ,
     * @param string array  $classid
     * @return string
     */
    protected function parseComma($classid)
    {
        return str_replace([';',':'], ',', $classid);
    }


    /**
     * 格式化表名，将 /. 转为 _ ，支持多级控制器
     * @param string $name
     * @return mixed
     */
    protected function parseTable($name = '')
    {
        if (!$name) {
            $name = $this->request->controller();
        }
        return str_replace(['/', '.'], '_', $name);
    }

    /**
     * 格式化类名，将 /. 转为 \\
     * 已废弃，请使用Loader::parseClass()
     * @param string $name
     * @return mixed
     */
    protected function parseClass($name = '')
    {
        if (!$name) {
            $name = $this->request->controller();
        }
        return str_replace(['/', '.'], '\\', $name);
    }

    /**
     * 将abc.def.Gh转为AbcDefGh
     * @param $string
     * @return mixed
     */
    protected function parseCamelCase($string)
    {
        return preg_replace_callback('/(\.|^)([a-zA-Z])/', function ($match) {
            return ucfirst($match[2]);
        }, $string);
    }

    /**
     * 记录方法或函数执行时间
     * 使用方法如下
     * $time_start = $this->getmicrotime(); //开始位置
     * $time_end = $this->getmicrotime();   //结束位置
     * $time = $time_end - $time_start;     //总耗时
     */
    public function getmicrotime()
    {
        list($usec, $sec) = explode(" ",microtime());
        return ((float)$usec + (float)$sec);
    }

}
?>